#!/usr/bin/env ruby

require 'logger'
require 'date'
require 'fileutils'

root_dir = File.expand_path("../../../", __FILE__)

enterprise_dir = "#{root_dir}/test/enterprise"
log_file = "#{enterprise_dir}/log/install.log"

#logger = Logger.new log_file
logger = Logger.new STDOUT

class AfterBreakdown

  def initialize(log_file, logger)
    @log_file = log_file
    @logger = logger
    if not ENV['TRAVIS'].nil?
      @ci = "TRAVIS"
    else
      @ci = "LOCAL"
    end
  end
  
  
  def shell_cmd(name, cmd)
    status = system cmd
    if status
      @logger.info "#{@ci} successful #{name} at: #{DateTime.now}"
    else
      @logger.warn "Failed:#{ci} #{name}  #{DateTime.now}"
    end
    status
  end
  
  def stop_rails(path)
    pd = "#{path}/tmp/pids"
    if File.exists? pd
      Dir.foreach pd do |f|
        if f.include? "server"
          File.new("#{pd}/#{f}").readlines.each do |l|
            @logger.info "Killing process id: #{l}"
            Process.kill("KILL", l.strip.to_i)
          end
          @logger.info "Removing pid file: #{pd}/#{f}"
          FileUtils.rm "#{pd}/#{f}"
        end
      end
    end
  end
  
end

logger.info "Travis after testing at: #{DateTime.now}"

Dir.chdir enterprise_dir

after = AfterBreakdown.new log_file, logger
after.stop_rails enterprise_dir

logger.info "Travis after script complete: #{DateTime.now}"